package top.jfunc.common.compress;

import top.jfunc.common.utils.ArrayUtil;
import top.jfunc.common.utils.IoUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 不提供压缩功能，原封不动返回
 * 在某些情况下方便程序的统一处理
 * @author xiongshiyan
 */
public class NoCompressor implements Compressor {
    @Override
    public byte[] compress(byte[] src, int offset, int length) throws CompressException {
        return copy(src, offset, length);
    }

    @Override
    public byte[] compress(byte[] src, byte[]... more) throws CompressException {
        return ArrayUtil.merge(src, more);
    }

    @Override
    public byte[] compress(InputStream src) throws CompressException {
        return readBytesFromStream(src);
    }

    @Override
    public byte[] unCompress(byte[] src, int offset, int length) throws CompressException {
        return copy(src, offset, length);
    }

    @Override
    public byte[] unCompress(InputStream src) throws CompressException {
        return readBytesFromStream(src);
    }

    protected byte[] readBytesFromStream(InputStream src) throws CompressException {
        try {
            return IoUtil.stream2Bytes(src);
        } catch (IOException e) {
            throw new CompressException(e);
        }
    }

    protected byte[] copy(byte[] src, int offset, int length) throws CompressException {
        //说明是整个数组
        if(0 == offset && src.length == length){
            return src;
        }

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
            outputStream.write(src, offset, length);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new CompressException(e);
        }

    }
}
